package com.edu.danmu;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * netty客户端
 */
public class NettyClient {
    public static final int PORT = 8888;
    public void start(){
        System.out.println("启动netty客户器");
        Scanner scanner = new Scanner(System.in);
        //工作线程组 用于执行IO
        EventLoopGroup workerGroup = new NioEventLoopGroup(2);
        try {
            //创建客户端的启动的对象
            Bootstrap bootstrap = new Bootstrap();
            //设置线程组
            bootstrap.group(workerGroup)
                    .channel(NioSocketChannel.class)       //设置通道类型
                    .handler(new ChannelInitializer<SocketChannel>() {  //创建通道的初始化器
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline()  //管道
                                    .addLast(new StringEncoder()) //添加字符串编码器
                                    .addLast(new StringDecoder()) //添加字符串解码器
                                    .addLast(new NettyClientHandler()); //添加自定义处理器
                        }
                    });
            //连接服务器 sync是将操作转为同步方式
            ChannelFuture sync = bootstrap.connect("127.0.0.1", PORT).sync();
            //发送消息给服务器
            while(true){
                String msg = scanner.nextLine();
                if("exit".equals(msg)){
                    break;
                }
                sync.channel().writeAndFlush(msg);
            }
            //关闭通道
//            sync.channel().closeFuture().sync();
        }catch (Exception ex){
            ex.printStackTrace();
        }finally {
            //关闭线程组
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new NettyClient().start();
    }
}
